#include "registerbox.h"
#include "ui_registerbox.h"
#include "myqq.h"

#include <QHostAddress>
#include <QCryptographicHash>

RegisterBox::RegisterBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RegisterBox)
{
    ui->setupUi(this);
}

RegisterBox::~RegisterBox()
{
    delete ui;
}

void RegisterBox::sendNewData(QString account, QString password)
{
    registerSocket = new QTcpSocket();
    registerSocket->connectToHost(QHostAddress("127.0.0.1"), 9999);
    if(!registerSocket->waitForConnected())
    {
        return ;
    }

    QString msg = "REGISTER#*#" + account + "*^*" + password;
    registerSocket->write(msg.toLatin1(), msg.toLatin1().length());
    if(!registerSocket->waitForReadyRead())
    {
        return;
    }

    QByteArray ba;
    ba.resize(registerSocket->bytesAvailable());
    registerSocket->read(ba.data(), ba.size());
    qDebug() << "in myqq client : " << ba.data();
    if(ba == "Success")
    {
        Myqq *w = new Myqq();
        w->show();
        close();
    }
    else
    {
        QMessageBox::warning(this, "Error", "Register fail !");
    }

}

void RegisterBox::on_pushButtonConfirm_clicked()
{
    /*
     * todo send new account and password to the database
    */
    if(ui->lineEditAccount->text().isEmpty() ||
            ui->lineEditPassword->text().isEmpty() ||
            ui->lineEditAgainPassword->text().isEmpty())
    {
        qDebug() << "Warning : " << "Please input text complete .";
        QMessageBox::warning(this, "Error", "Please input text complete !");
    }
    else if(ui->lineEditPassword->text() != ui->lineEditAgainPassword->text())
    {
        qDebug() << "Error : " << "Password Error !";
        QMessageBox::warning(this, "Error", "Password is not correct !");
    }
    else
    {
        qDebug() << "Success : " << "Input correct";
#if 0
        QString accountmd5;
        QString passwordmd5;
        QByteArray bamd5;

        bamd5 = QCryptographicHash::hash(ui->lineEditAccount->text())
#endif
        sendNewData(QString(ui->lineEditAccount->text()), QString(ui->lineEditPassword->text()));
    }
}
